package com.lanlian.cayman.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.SelectSheetDialog;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PreRegisterExtendInfo;
import com.lanlian.commonlib.bean.RegisterEnumInfo;
import com.lanlian.commonlib.bean.ReqRegisterEnum;
import com.lanlian.commonlib.bean.RespRegisterEnumList;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.MaxTextLengthFilter;
import com.lanlian.utillib.WorksSizeCheckUtil;

import java.util.ArrayList;
import java.util.Map;

import static com.lanlian.cayman.activity.UpdateOpenAccountActivity.respPreRegister;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/14 14:18
 *     desc   : 注册开户第三步，账户信息
 *     version: 1.0
 * </pre>
 */
@SuppressLint("ValidFragment")
public class UpdateRegisterThreeFragment extends BaseFragment implements View.OnClickListener {

    private LinearLayout mLayAssetsSource;
    private LinearLayout mLayAssetsType;
    private LinearLayout mLayNetAssets;
    private LinearLayout mLayAnnualIncome;
    private EditText mEtBroken;
    private TextView mTvAssetsSource;
    private TextView mTvAssetsType;
    private TextView mTvNetAssets;
    private TextView mTvAnnualIncome;
    private TextView mTvNext;
    private TextView mTvPrevious;

    private boolean mIsEditHasContent;
    private boolean mIsFirst = true;

    private String mAssetsSourceStr;
    private String mAssetsTypeStr;
    private String mNetAssetsStr;
    private String mAnnualIncomeStr;

    private SelectSheetDialog dialog1;
    private SelectSheetDialog dialog2;
    private SelectSheetDialog dialog3;
    private SelectSheetDialog dialog4;

    public static Map<String, ArrayList<RegisterEnumInfo>> registerEnumMap;
    private OnPreviousClickListener mOnPreviousClickListener;

    public interface OnPreviousClickListener {
        void onNextClick();

        void onPreviousClick();
    }

    public UpdateRegisterThreeFragment(OnPreviousClickListener onPreviousClickListener) {
        this.mOnPreviousClickListener = onPreviousClickListener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register_three_update, null);
        initView(view);
        setListeners();
        getRegisterEnum();
        return view;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mLayAssetsSource = view.findViewById(R.id.lay_assets_source);
        mLayAssetsType = view.findViewById(R.id.lay_assets_type);
        mLayNetAssets = view.findViewById(R.id.lay_net_assets);
        mLayAnnualIncome = view.findViewById(R.id.lay_annual_income);
        mEtBroken = view.findViewById(R.id.et_broken);
        mTvNext = view.findViewById(R.id.tv_next);
        mTvPrevious = view.findViewById(R.id.tv_previous);
        mTvAssetsSource = view.findViewById(R.id.tv_assets_source);
        mTvAssetsType = view.findViewById(R.id.tv_assets_type);
        mTvNetAssets = view.findViewById(R.id.tv_net_assets);
        mTvAnnualIncome = view.findViewById(R.id.tv_annual_income);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvNext.setOnClickListener(this);
        mTvPrevious.setOnClickListener(this);
        mLayAssetsSource.setOnClickListener(this);
        mLayAnnualIncome.setOnClickListener(this);
        mLayAssetsType.setOnClickListener(this);
        mLayNetAssets.setOnClickListener(this);
        WorksSizeCheckUtil worksSizeCheckUtil = new WorksSizeCheckUtil(mTvNext);
        worksSizeCheckUtil.addAllEditText(mTvAssetsSource, mTvAssetsType, mTvNetAssets, mTvAnnualIncome);
        worksSizeCheckUtil.setChangeListener(new WorksSizeCheckUtil.IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                mIsEditHasContent = isHasContent;
                checkData();
            }
        });
        mEtBroken.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                LLApplication.reqUpdateUserRegister.setBankruptcyDesc(s.toString());
            }
        });
        mEtBroken.setFilters(new InputFilter[]{new MaxTextLengthFilter(150, getActivity())});
    }

    private void initDialog() {
        dialog1 = new SelectSheetDialog(getActivity(), "主要资产来源",
                AbsListView.CHOICE_MODE_MULTIPLE, registerEnumMap.get("AssetSources"));
        dialog1.setOnFinishClickListener(new SelectSheetDialog.OnFinishClickListener() {
            @Override
            public void onFinishClick(ArrayList<RegisterEnumInfo> strings) {
                if (!CommonUtils.isListEmpty(strings)) {
                    StringBuilder s = new StringBuilder();
                    StringBuilder s2 = new StringBuilder();
                    for (RegisterEnumInfo string : strings) {
                        if (strings.indexOf(string) == strings.size() - 1) {
                            s.append(string.getContent());
                            s2.append(string.getID());
                        } else {
                            s.append(string.getContent()).append("，");
                            s2.append(string.getID()).append(",");
                        }
                    }
                    mAssetsSourceStr = s2.toString();
                    mTvAssetsSource.setText(s.toString());
                    LLApplication.reqUpdateUserRegister.setAssetsSource(mAssetsSourceStr);
                } else {
                    mAssetsSourceStr = "";
                    mTvAssetsSource.setText("");
                    LLApplication.reqUpdateUserRegister.setAssetsSource(mAssetsSourceStr);
                }
            }
        });
        dialog2 = new SelectSheetDialog(getActivity(), "资产类型",
                AbsListView.CHOICE_MODE_MULTIPLE, registerEnumMap.get("AssetType"));
        dialog2.setOnFinishClickListener(new SelectSheetDialog.OnFinishClickListener() {
            @Override
            public void onFinishClick(ArrayList<RegisterEnumInfo> strings) {
                if (!CommonUtils.isListEmpty(strings)) {
                    StringBuilder s = new StringBuilder();
                    StringBuilder s2 = new StringBuilder();
                    for (RegisterEnumInfo string : strings) {
                        if (strings.indexOf(string) == strings.size() - 1) {
                            s.append(string.getContent());
                            s2.append(string.getID());
                        } else {
                            s.append(string.getContent()).append("，");
                            s2.append(string.getID()).append(",");
                        }
                    }
                    mAssetsTypeStr = s2.toString();
                    mTvAssetsType.setText(s.toString());
                    LLApplication.reqUpdateUserRegister.setAssetsType(mAssetsTypeStr);
                } else {
                    mAssetsTypeStr = "";
                    mTvAssetsType.setText("");
                    LLApplication.reqUpdateUserRegister.setAssetsType(mAssetsTypeStr);
                }
            }
        });
        dialog3 = new SelectSheetDialog(getActivity(), "净资产",
                AbsListView.CHOICE_MODE_SINGLE, registerEnumMap.get("NetAsset"));
        dialog3.setOnFinishClickListener(new SelectSheetDialog.OnFinishClickListener() {
            @Override
            public void onFinishClick(ArrayList<RegisterEnumInfo> strings) {
                if (!CommonUtils.isListEmpty(strings)) {
                    mTvNetAssets.setText(strings.get(0).getContent());
                    mNetAssetsStr = strings.get(0).getID();
                    LLApplication.reqUpdateUserRegister.setNetAssets(mNetAssetsStr);
                }
            }
        });
        dialog4 = new SelectSheetDialog(getActivity(), "年收入",
                AbsListView.CHOICE_MODE_SINGLE, registerEnumMap.get("AnnualIncome"));
        dialog4.setOnFinishClickListener(new SelectSheetDialog.OnFinishClickListener() {
            @Override
            public void onFinishClick(ArrayList<RegisterEnumInfo> strings) {
                if (!CommonUtils.isListEmpty(strings)) {
                    mTvAnnualIncome.setText(strings.get(0).getContent());
                    mAnnualIncomeStr = strings.get(0).getID();
                    LLApplication.reqUpdateUserRegister.setUserIncome(mAnnualIncomeStr);
                }
            }
        });
    }

    public void setPreRegisterInfo() {
        if (respPreRegister != null && mIsFirst && registerEnumMap != null) {
            mIsFirst = false;
            if (respPreRegister.getUserExtendInfo() == null) {
                return;
            }
            PreRegisterExtendInfo registerExtendInfo = respPreRegister.getUserExtendInfo();
            mAssetsSourceStr = registerExtendInfo.getAssetsSource();
            if (!TextUtils.isEmpty(mAssetsSourceStr)) {
                String[] assetsSourceStrs = mAssetsSourceStr.split(",");
                ArrayList<Integer> ids1 = new ArrayList<>();
                StringBuilder s1 = new StringBuilder();
                for (int i = 0; i < assetsSourceStrs.length; i++) {
                    for (RegisterEnumInfo assetSource : registerEnumMap.get("AssetSources")) {
                        if (assetSource.getID().equals(assetsSourceStrs[i])) {
                            ids1.add(registerEnumMap.get("AssetSources").indexOf(assetSource));
                            if (i == assetsSourceStrs.length - 1) {
                                s1.append(assetSource.getContent());
                            } else {
                                s1.append(assetSource.getContent()).append("，");
                            }
                            break;
                        }
                    }
                }
                mTvAssetsSource.setText(s1.toString());
                dialog1.setMultiChecked(ids1);
            }

            mAssetsTypeStr = registerExtendInfo.getAssetsType();
            if (!TextUtils.isEmpty(mAssetsTypeStr)) {
                String[] assetsTypeStrs = mAssetsTypeStr.split(",");
                ArrayList<Integer> ids2 = new ArrayList<>();
                StringBuilder s2 = new StringBuilder();
                for (int i = 0; i < assetsTypeStrs.length; i++) {
                    for (RegisterEnumInfo assetSource : registerEnumMap.get("AssetType")) {
                        if (assetSource.getID().equals(assetsTypeStrs[i])) {
                            ids2.add(registerEnumMap.get("AssetType").indexOf(assetSource));
                            if (i == assetsTypeStrs.length - 1) {
                                s2.append(assetSource.getContent());
                            } else {
                                s2.append(assetSource.getContent()).append("，");
                            }
                            break;
                        }
                    }
                }
                mTvAssetsType.setText(s2.toString());
                dialog2.setMultiChecked(ids2);
            }

            mNetAssetsStr = registerExtendInfo.getNetAssets();
            if (!TextUtils.isEmpty(mNetAssetsStr)) {
                for (RegisterEnumInfo assetSource : registerEnumMap.get("NetAsset")) {
                    if (assetSource.getID().equals(mNetAssetsStr)) {
                        mTvNetAssets.setText(assetSource.getContent());
                        dialog3.setSingleChecked(registerEnumMap.get("NetAsset").indexOf(assetSource));
                        break;
                    }
                }
            }

            mAnnualIncomeStr = registerExtendInfo.getUserIncome();
            if (!TextUtils.isEmpty(mAnnualIncomeStr)) {
                for (RegisterEnumInfo assetSource : registerEnumMap.get("AnnualIncome")) {
                    if (assetSource.getID().equals(mAnnualIncomeStr)) {
                        mTvAnnualIncome.setText(assetSource.getContent());
                        dialog4.setSingleChecked(registerEnumMap.get("AnnualIncome").indexOf(assetSource));
                        break;
                    }
                }
            }

            mEtBroken.setText(registerExtendInfo.getBankruptcyDesc());

            LLApplication.reqUpdateUserRegister.setAssetsSource(mAssetsSourceStr);
            LLApplication.reqUpdateUserRegister.setAssetsType(mAssetsTypeStr);
            LLApplication.reqUpdateUserRegister.setNetAssets(mNetAssetsStr);
            LLApplication.reqUpdateUserRegister.setUserIncome(mAnnualIncomeStr);
            LLApplication.reqUpdateUserRegister.setBankruptcyDesc(registerExtendInfo.getBankruptcyDesc());
        }
    }

    private void checkData() {
        if (mIsEditHasContent) {
            mTvNext.setEnabled(true);
            mTvNext.setBackgroundResource(R.mipmap.login_btn);
        } else {
            mTvNext.setEnabled(false);
            mTvNext.setBackgroundResource(R.drawable.bg_click_false);
        }
    }

    private void getRegisterEnum() {
        VolleyRequestUtils.getInstance().getRegisterEnum(this.toString(), new ReqRegisterEnum(), new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                RespRegisterEnumList respRegisterEnumList = (RespRegisterEnumList) response;
                registerEnumMap = respRegisterEnumList.getData();
                initDialog();
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_next:
                mOnPreviousClickListener.onNextClick();
                break;
            case R.id.tv_previous:
                mOnPreviousClickListener.onPreviousClick();
                break;
            case R.id.lay_assets_source:
                if (dialog1 != null) {
                    dialog1.showDialog();
                }
                break;
            case R.id.lay_assets_type:
                if (dialog2 != null) {
                    dialog2.showDialog();
                }
                break;
            case R.id.lay_net_assets:
                if (dialog3 != null) {
                    dialog3.showDialog();
                }
                break;
            case R.id.lay_annual_income:
                if (dialog4 != null) {
                    dialog4.showDialog();
                }
                break;
            default:
                break;
        }
    }
}
